<?php

declare(strict_types=1);

namespace app\admin\middleware;

use AlibabaCloud\Client\Request\Request;
use app\common\lib\Show;

/**
 * 使用中间件处理是否登录
 * Class Auth
 * @package app\admin\middleware
 */
class Auth
{
    public $accessToken = "";
    public $adminId = 0;
    public $departmentId = 0;

    public function handle(\app\Request $request, \Closure $next)
    {
        $this->accessToken=$request->header('Authori-zation');

        //http请求前 进入控制器前
        $allow=['captcha','login'];
        if(!in_array($request->pathinfo(),$allow)){
            //不在白名单请求地址中，则需要验证登录状态

            if(!$this->isLogin()){
                return Show::error([],empty($this->accessToken)?'请先登录':'登录已过期请重新登录',config('status.not_login'));
            }

            $request->withMiddleware(['adminId' =>$this->adminId, 'departmentId'=>$this->departmentId, 'token'=>$this->accessToken]); //前置中间件传参，后置中间件无法向控制器传参
        }

        $response = $next($request);//后置中间件，http请求完成之后，才开始执行中间件的代码

        //http请求后 控制器代码执行后

        return $response;
    }

    /**
     * 判断是否登录
     * @return bool
     */
    public function isLogin(): bool
    {
        $adminInfo = cache(config("redis.admin_token_pre") . $this->accessToken);
        if (!$adminInfo) {
            return false;
        }
        if (!empty($adminInfo['id']) && !empty($adminInfo['username']) && (!empty($adminInfo['department_id'])||$adminInfo['department_id']==0)) {
            $this->adminId = $adminInfo['id'];
            $this->departmentId = $adminInfo['department_id'];
            return true;
        }
        return false;
    }
}
